﻿//Description:Camstar和DataGatWay服务监控类
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:Wangjh
//create Date:2024-12-18
//Rewriter:
//Rewrite Date:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DatabaseAccess.DBUtility;
using System.Configuration;
using External.APICalling;
using BusinessRule.Common;
using BusinessRule.DTO;
using System.Threading;
using System.IO;

namespace MesServiceMonitor
{
    public class CamstarAndDataGatWay
    {
        private static readonly string camstarUser = ConfigurationManager.AppSettings["CamstarUserName"];
        private static readonly string camstarPwd = ConfigurationManager.AppSettings["CamstarPassword"];
        private static readonly string xmlPath = ConfigurationManager.AppSettings["XmlPath"];

        public CamstarAndDataGatWay(string xml)
        {
            this.lastXml = xml;
        }
        //上次定时循环时的xml个数
        public string lastXml;

        /// <summary>
        /// 入口
        /// 测试camstarapi是否正常，若异常则重启camstarserver服务和datagatway服务
        /// </summary>
        public void RunMain()
        {
            if (!testCamstarApi())
            {
                LogHelp.WriteLog("Camstar Api调用异常，开始重启服务");
                //重启Camstar Server和DataGatwayService
                CommonMethod.stopService("DataGatwayService");
                CommonMethod.stopService("Camstar Server");

                CommonMethod.startService("Camstar Server");
                //等待2分钟后再启动下一个服务
                Thread.Sleep(1000 * 60 * 2);
                CommonMethod.startService("DataGatwayService");
            }
            //监控DataXML下的文件,按.xml文件【最后写入时间】正排序取第一个文件存放，第二次进入判断上次存放的文件是否还存在，若存在,则判定DataGatwayService假死。重新启动
            if (!DataGatwayServiceMonitor()) {
                LogHelp.WriteLog("DataGatwayService服务假死，开始重启服务");
                //重启Camstar Server和DataGatwayService
                CommonMethod.stopService("DataGatwayService");
                //等待1分钟后再启动下一个服务
                Thread.Sleep(1000 * 60 * 1);
                CommonMethod.startService("DataGatwayService");
            }
        }

        /// <summary>
        /// 监控DataXML下的文件,按.xml文件【最后写入时间】正排序取第一个文件存放，第二次进入判断上次存放的文件是否还存在，若存在,则判定DataGatwayService假死。重新启动
        /// add by longb 2024-12-19
        /// </summary>
        bool DataGatwayServiceMonitor()
        {
            bool isSuccess = string.IsNullOrWhiteSpace(this.lastXml);//为空：true
            if (!isSuccess && File.Exists(this.lastXml))//判断上一次的文件是否还存在,若存在，则假死
            {
                isSuccess = false;
            }
            //查询文件夹下所有xml文件，按时间正排序
            DirectoryInfo di = new DirectoryInfo(xmlPath);
            FileInfo[] files = di.GetFiles();
            var sortedFiles = files.Where(p=>p.Extension.Contains(".xml")).OrderBy(f => f.LastWriteTime).ToList();
            if (sortedFiles.Count > 0)
            {
                this.lastXml = sortedFiles[0].FullName;//取最小时间的文件作为判断依据
            }
            else {
                this.lastXml = string.Empty;
                isSuccess = true;
            }
            return isSuccess;
        }

        /// <summary>
        /// 测试camstar api是否正常
        /// </summary>
        /// <returns></returns>
        bool testCamstarApi()
        {
            try
            {
                CamstarClientAPI api = new CamstarClientAPI(camstarUser, camstarPwd);

                List<ClientAPIEntity> dataList = new List<ClientAPIEntity>();

                ClientAPIEntity dataEntity;
                dataEntity = new ClientAPIEntity();
                dataEntity.ClientDataTypeEnum = DataTypeEnum.DataField;
                dataEntity.ClientInputTypeEnum = InputTypeEnum.Details;
                dataEntity.ClientDataName = "Name";
                dataEntity.ClientDataValue = "1";
                dataList.Add(dataEntity);

                string msg = "";
                bool isSuccess = false;

                if (DatabaseHelper.GetSingle("select 1 from productfamily pf where pf.productfamilyname='1'") == null)
                {
                    isSuccess = api.CreateModelByStandard("ProductFamilyMaintDoc", "ProductFamilyMaint", "", dataList, ref msg);
                }
                else
                {
                    isSuccess = api.UpdateModelByStandard("ProductFamilyMaintDoc", "ProductFamilyMaint", "1", "", dataList, ref msg);
                }
                if (!isSuccess)
                {
                    LogHelp.WriteLog("CamstarApi异常" + msg);
                }
                return isSuccess;
            }
            catch (Exception ex)
            {
                LogHelp.WriteLog("CamstarApi异常" + ex.Message);
                return false;
            }

        }

    }
}
